import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserSrote } from '@/stores/modules/user'

import { md5Encrypt } from './md5';
import { htmlDecodeByRegExp } from './htmlDecode';

const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 8000
});

// 添加请求拦截器
request.interceptors.request.use(function (config) {
    const userSrote = useUserSrote()
    // 加密签名
    const data = config.data || {};
    const params = Object.keys(data)
      .sort()
      .map(key => `${key}=${htmlDecodeByRegExp(data[key])}`)
      .join('&');
    const signature = md5Encrypt(params+`1IJWqH8Rh9/NTPCc6AGJujcPPFs4w4+Nbualhz7DbAgQ5k0Hd8ZJZg13yF+/mnz`);
    console.log("===")
    console.log(params)
    config.headers['signature'] = signature;

    // const str = md5(`account=${userSrote.account}&password=${userSrote.password}1IJWqH8Rh9/NTPCc6AGJujcPPFs4w4+Nbualhz7DbAgQ5k0Hd8ZJZg13yF+/mnz`)
    // 在发送请求之前做些什么
    //在请求中携带token(这里创建userSrote对象必须写在这里，不能写在外面)
    // config.headers['signature'] = str
    config.headers['Accept'] = 'multipart/form-data'
    config.headers['Content-Type'] = 'multipart/form-data'
    if(userSrote.token){
        config.headers.token = userSrote.token
    }

    return config;
}, function (error: any) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(function (response: { data: any; }) {
    
    return response.data;
}, function (error: { code: any; }) {
    console.log(error)
    let msg = ''
    const code = error.code
    switch (code) {
        case 401:
            msg = 'token过期'
            break
        case 403:
            msg = '无权访问'
            break
        case 404:
            msg = '请求地址错误'
            break
        case 500:
            msg = '服务器异常'
            break
        default:
            msg = '网络异常'
            break
    }
    ElMessage.error(msg)
    return Promise.reject(error);
});

export default request;